#include "bitmap.h"
#include "string.h"
#include "global.h"
#include "debug.h"
void bitmap_init(struct bitmap* btmp)
{
    memset(btmp->bits,0,btmp->btmp_bytes_len);
}


bool bitmap_scan_test(struct bitmap* btmp, uint32_t bit_idx)
{
    uint32_t byte_idx = bit_idx / 8;
    uint32_t bit_offset = bit_idx % 8;
    uint8_t bit_value = btmp->bits[byte_idx];
    return (bit_value >> bit_offset) & BITMAP_MASK;
}

int bitmap_scan(struct bitmap* btmp, uint32_t cnt)
{
    if(cnt <=0 ){
        return -1;
    }
    uint32_t targetCnt = 0;

    uint32_t bitMapOffset = 0;
    uint32_t bitsSize = btmp->btmp_bytes_len * 8;
    for(bitMapOffset = 0 ; bitMapOffset <  bitsSize; bitMapOffset ++){
        if( !bitmap_scan_test(btmp,bitMapOffset) ){
            targetCnt++; //当位图中的当前位是0
        }else{
            targetCnt = 0;
        }

        if(targetCnt == cnt){
            return bitMapOffset - cnt + 1;
        }
        
    }

    return -1;
}

void bitmap_set(struct bitmap* btmp, uint32_t bit_idx, int8_t value)
{
    ASSERT(value == 0 || value == 1);
    uint32_t byte_idx = bit_idx / 8;
    uint32_t bit_offset = bit_idx % 8;
    if(value){
         btmp->bits[byte_idx] |= (BITMAP_MASK << bit_offset);
    }else{
         btmp->bits[byte_idx] &= ~(BITMAP_MASK << bit_offset);
    }
}
